package ru.chezclif.lern.conread;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import ru.chezclif.lern.conread.parser.PathDataInputProperties;

/**
 * Наполнение хранилища данных из файла .properies
 * 
 * @author Vit
 * 
 */
public class PropertyParser implements PathDataInputProperties {

	@Override
	/**
	 * По параметру filePath находится файл, из него получают настройки и сохраняют в объект propertyBuffer
	 * 
	 *@param filePath полный путь к оперируемому файлу
	 *@param propertyBuffer хранилище данных для заполнения
	 */
	public void parseFile(String fileName, DataBuffer propertyBuffer) {
		Preconditions.notBlank(fileName);
		Preconditions.notNull(fileName);
		Preconditions.notNull(propertyBuffer);
		Properties settings = new Properties();
		try {
			File propertyFile = new File(fileName);
			FileInputStream fileInputStream = new FileInputStream(propertyFile);
			InputStream inputStream = fileInputStream;
			settings.load(inputStream);
			inputStream.close();
			fileInputStream.close();
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			if (!(bufferedReader.ready())) {
				throw new ru.chezclif.lern.conread.exceptions.EmptyFileExeption(fileName);
			}
			String standartLine = "";
			String endLineString = "";
			boolean furstLine = true;
			boolean endline = false;
			while ((standartLine = bufferedReader.readLine()) != null) {
				if (!(standartLine.trim().equals(""))) {
					if ((furstLine) && (standartLine.charAt(0) == '#')) {
						propertyBuffer.setHeaderComment(standartLine.substring(1));
					}
					if (furstLine) {
						furstLine = !furstLine;
					}
					endLineString = standartLine;
				}
			}
			endline = true;
			if (!(endLineString.trim().equals(""))) {
				if ((endline) && (endLineString.charAt(0) == '#')) {
					propertyBuffer.setFooterComment(endLineString.substring(1));
				}
			}
			bufferedReader.close();
		} catch (FileNotFoundException e) {
			throw new ru.chezclif.lern.conread.exceptions.FileNotFoundException(e, fileName);
		} catch (IOException e) {
			throw new ru.chezclif.lern.conread.exceptions.FileNotFoundException(e, fileName);
		}
		Enumeration propertyNameList = settings.keys();
		String key = "";
		String value = "";
		for (Enumeration e = propertyNameList; e.hasMoreElements();) {
			key = (String) e.nextElement();
			value = settings.getProperty(key);
			propertyBuffer.setSetting(key, value);
		}
	}
}
